var express = require('express');
var router = express.Router();
var http = require('http');
var url = require('url');


/* 跨域問題*/
router.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});
/* GET home page. */
router.get('/lunbo', function(req, res) {
    var t = req.query.time;
    var url = 'http://m.maizuo.com/v4/api/billboard/home?__t=' + t;
    http.get(url, function(response) {
        var data = '';
        response.on('data', function(chunk) {
            data += chunk;
        })
        response.on('end', function() {
            res.send(data);
        })
    })
})

// now  http://m.maizuo.com/v4/api/film/now-playing?__t=1495857563310&page=1&count=5

router.get('/nowplaying', function(req, res) {
    var t = req.query.time;
    var url = 'http://m.maizuo.com/v4/api/film/now-playing?__t=' + t + '&page=1&count=5';
    http.get(url, function(response) {
        var data = '';
        response.on('data', function(chunk) {
            data += chunk;
        })
        response.on('end', function() {
            res.send(data);
        })
    });
})

// http://m.maizuo.com/v4/api/film/coming-soon?__t=1495860196850&page=1&count=3
router.get('/comingsoon', function(req, res) {
        var t = req.query.time;
        var url = 'http://m.maizuo.com/v4/api/film/coming-soon?__t' + t + '&page=1&count=3';
        http.get(url, function(response) {
            var data = '';
            response.on('data', function(chunk) {
                data += chunk;
            })
            response.on('end', function() {
                res.send(data);
            })
        });
    })
    // http://m.maizuo.com/v4/api/film/3664?__t=1495872720546
router.get(/\d$/, function(req, res) {
    var t = req.query.time;
    var id = url.parse(req.url).pathname.substr(1);
    console.log(id);
    var url1 = ' http://m.maizuo.com/v4/api/film/' + id + '?__t=' + t;

    http.get(url1, function(response) {
        var data = '';
        response.on('data', function(chunk) {
            data += chunk;
        })
        response.on('end', function() {
            res.send(data);
        })
    })
})


router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

module.exports = router;